import json
import time
import hmac
import hashlib
import base64
import urllib.parse
import requests


def get_args(secret):
    timestamp = str(round(time.time() * 1000))
    secret_enc = secret.encode('utf-8')
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
    return {'timestamp': timestamp, 'sign': sign}


class DingRobot:

    def __init__(self, url, secret):
        self.url = url
        self.secret = secret

    @staticmethod
    def get_instance(config):
        return DingRobot(config['url'], config['secret'])

    def send_msg(self, ajax_data):
        args = get_args(self.secret)
        url = f"{self.url}&timestamp={args['timestamp']}&sign={args['sign']}"

        # data_string = json.dumps(data)
        # headers={'Content-Type': 'application/json;charset=utf-8'}
        requests.post(url, json=ajax_data)
